<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称" :model="spu">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!-- 上传图片，action为上传的地址，list-type为文件类型，on-preview:图片预览的时候会触发 -->
        <!-- on-remove:当删除图片的时候会触发，on-preview:图片预览功能 file-list为展示图片的列表-->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handlerSuccess"
          :file-list="spuImageList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <!-- 对话框 -->
        <!-- visible控制显示与隐藏，.sync指双向，当点了取消就会隐藏，或改了这个值也会隐藏 -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndAttrName"
        >
          <!-- 这里收集了没有选择的销售属性的id和名字 -->
          <el-option
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
            v-for="(unselect, index) in unSelectSaleAttr"
            :key="unselect.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <!-- 展示的是当前SPU属于自己的销售属性 -->
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <!--  " -->
              <!-- el-tag:用户展示已有属性值列表的数据的 -->
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                >{{ tag.saleAttrValueName }}</el-tag
              >
              <!-- elementUI自带的span与input切换 -->

              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
                @keyup.enter.native="handleInputConfirm(row)"
              >
              </el-input>
              <!-- @click="showInput" -->
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <!-- 删除属性值 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrChangeSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      //这里要先初始化空的信息，因为要添加的时候展示出来为空
      spu: {
        //三级分类的id
        category3Id: 0,
        //描述
        description: "",
        //spu名称
        spuName: "",
        //平台的id
        tmId: "",
        //收集SPU图片的信息
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        //平台属性与属性值收集
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      },
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储SPU图片的数据
      saleAttrList: [], //销售属性的数据（项目全部的销售属性）
      attrIdAndAttrName: "", //收集未选择的销售属性的i
    };
  },
  methods: {
    //删除照片墙中某一张图的回调
    handleRemove(file, fileList) {
      //file为删除的那个图片，fileList为删除后剩余的图片
      console.log(file, fileList);
      this.spuImageList = fileList;
    },
    //图片墙预览
    handlePictureCardPreview(file) {
      //将图片的地址给这个属性
      this.dialogImageUrl = file.url;
      //然后再把对话框显示出来
      this.dialogVisible = true;
    },
    //照片墙图片上传成功后
    handlerSuccess(response, file, fileList) {
      //上传成功后收集图片的信息,response是上传图片后，服务器返回的信息
      //file是上传的那个图片的信息，flieList是上传后，全部图片的信息

      this.spuImageList = fileList;
    },
    cancel() {
      this.$emit("changeScene", {
        scene: 0,
        flag: this.spu.tmId ? "修改" : "添加",
      });
      //取消要清理数据
      //合并对象，this.$options.data就相当于再执行一下data
      //也就是把现在的this._data变为了最开始的样子，也就是清空
      Object.assign(this._data, this.$options.data());
    },
    //初始化SPU数据
    async initSpuData(spu) {
      let spuResult = await this.$API.spu.reqSpuById(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      //获取品牌的信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //获取spu图片的数据
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code == 200) {
        //因为图片墙要数组，而且里面一定要name和url，所以要处理一下
        let listArr = spuImageResult.data;
        listArr.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = listArr;
      }
      //获取平台全部的销售属性
      let saleResult = await this.$API.spu.reqAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    //添加新的销售属性
    addSaleAttr() {
      // 把收集的销售属性分割出来
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueLis: [],
      };
      //添加新的销售属性
      this.spu.spuSaleAttrList.push(newSaleAttr);
      //再清空数据，方便之后添加
      this.attrIdAndAttrName = "";
    },
    //添加销售属性的值
    addSaleAttrValue(row) {
      //给每一个销售属性值加一个属性，控制是input与span的切换
      this.$set(row, "inputVisible", true);
      //添加完一个之后，要把后面的清空，方便之后再添加
      this.$set(row, "inputValue", "");
    },
    //input失去焦点时
    handleInputConfirm(row) {
      //当input失去焦点的时候，要把里面的数据给span并切换成span
      const { baseSaleAttrId, inputValue } = row;
      //新增的销售属性值不能为空
      if (inputValue.trim() == "") {
        this.$message("属性值不能为空");
        return;
      }
      //也不能重复,是否都满足不为当前input中的值
      console.log(row.hasOwnProperty("spuSaleAttrValueList"));
      //如果没有代表当前没有属性值，所以不用判断
      let result = true;
      if (row.hasOwnProperty("spuSaleAttrValueList")) {
        result = row.spuSaleAttrValueList.every(
          (item) => item.saleAttrValueName != inputValue
        );
      } else {
        //如果没有加一个空数组，要不然后面不能push
        row.spuSaleAttrValueList = [];
      }

      //有一个不满足，再返回false
      if (!result) {
        this.$message("属性值不能重复");
        return;
      }
      //满足条件后，新增
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      //再修改inputVisible，隐藏button
      row.inputVisible = false;
    },
    //保存按钮
    async addOrChangeSpu() {
      //在给服务器发请求之前，要先整理参数
      //图片列表只要带imageName和imageUrl
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imageName: item.name,
          imageUrl: (item.response && item.response.data) || item.url,
        };
      });
      //再发请求
      let result = await this.$API.spu.reqChangeOrAddSpu(this.spu);
      if (result.code == 200) {
        this.$message({ type: "success", message: "保存成功" });
        //通知父组件，回到场景0
        this.$emit("changeScene", {
          scene: 0,
          flag: this.spu.tmId ? "修改" : "添加",
        });
      }

      //再清除该组件的数据
      Object.assign(this._data, this.$options.data());
    },
    //添加SPU的回调
    async addSpuData(category3Id) {
      //收集三级分类
      this.spu.category3Id = category3Id;
      //添加的时候只要两个请求就行了
      //获取品牌的信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //获取平台全部的销售属性
      let saleResult = await this.$API.spu.reqAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
  },
  computed: {
    //计算出用户未选中的销售属性
    unSelectSaleAttr() {
      let result = this.saleAttrList.filter((item) => {
        // every遍历会返回一个布尔值
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
      return result;
    },
  },
};
</script>

<style>
</style>